<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      title="客户跟进"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @selection-change="setCompanyIds"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button v-auth="'add'" icon="Plus" type="primary" @click="openDrawer('新增')"> 新增客户跟进 </el-button>
      </template>
      <template #typeId="scope">
        {{ conversionDisplay(scope.row.typeId, dict["customerFollowing"]) }}
      </template>
      <template #visitTime="scope">
        {{ conversionDate(scope.row.visitTime) }}
      </template>
      <template #nextVisitTime="scope">
        {{ conversionDate(scope.row.nextVisitTime) }}
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button v-auth="'get'" type="primary" link @click="openDrawer('查看', scope.row)"> 查看 </el-button>
        <el-button v-auth="'update'" type="primary" link @click="openDrawer('编辑', scope.row)"> 编辑 </el-button>
        <el-button v-auth="'delete'" type="primary" link @click="deleteAccount(scope.row)"> 删除 </el-button>
      </template>
    </ProTable>
    <CustomerDrawer ref="drawerRef" />

    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, getCurrentInstance, computed } from "vue"; // onMounted
import { User, Dict } from "@/api/interface";
import dayjs from "dayjs";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import CustomerDrawer from "./CustomerDrawer.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { getParamByParentIdList } from "@/api/modules/sys"; // exportUserInfo,BatchAddUser
import { getFollowPage, addFollow, updateFollow, delFollow, getFollowDetail } from "@/api/modules/customer";
import { useUserStore } from "@/stores/modules/user";
import { useRouter } from "vue-router";

const cxt = getCurrentInstance();
const dict = cxt?.appContext.config.globalProperties.$dict;
let dictList: Dict.ResDictList = reactive({});

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ type: 1 });
// hook
const userStore = useUserStore();
const router = useRouter();
// computed
const isMe = computed(() => {
  return router.currentRoute.value.path === "/system/customerFollowing/profile";
});
// 获取字典数据
const getDicList = async (params: Dict.ResDictList) => {
  const { data } = await getParamByParentIdList(params);
  return data || [];
};
// 转换显示
const conversionDisplay = (id: string, type: string) => {
  const listItem = dictList[type]?.find(item => item.id === id);
  return listItem?.name;
};
// 处理显示时间
const conversionDate = (date: string) => {
  const parsedDate = dayjs(date);
  return parsedDate.isValid() ? parsedDate.format("YYYY-MM-DD") : "--";
};
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  console.log(data.records);
  // 增加省市区的返回值
  data.records = data.records.map(item => {
    item.addressed = item.provinceCode
      ? [item.provinceCode, item.cityCode, item.districtCode].filter(item => item && item.trim())
      : [];
    // item.companyProductsed = (item.companyProducts && item.companyProducts.map(itm => itm.productModelId)) || [];
    return item;
  });
  console.log(data.records);
  // 处理字段文字
  return {
    list: data.records,
    total: Number(data.total),
    pageNum: Number(data.current),
    pageSize: Number(data.size)
  };
};
// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = async (params: any) => {
  const list: string[] = [dict.customerFollowing, dict.customerStatus, dict.customerStage];
  dictList = await getDicList({ parentIdList: list.join(",") });
  const newParams = {
    currentPage: params.pageNum,
    searchKey: params.searchKey ? params.searchKey : "",
    typeId: params.typeId,
    userId: isMe.value ? userStore.userInfo.id : undefined
  };
  return getFollowPage(newParams);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
// const { BUTTONS } = useAuthButtons();
// 自定义渲染表头（使用tsx语法）
// const headerRender = (scope: HeaderRenderScope<User.ResUserList>) => {
//   return <el-button type="primary">{scope.column.label}</el-button>;
// };
// 表格配置项
const columns: ColumnProps<User.ResUserList>[] = [
  { type: "selection", width: 80 },
  { prop: "id", label: "ID", isShow: false },
  { prop: "companyName", label: "客户公司名称" },
  { prop: "content", label: "	跟进内容", search: { el: "input", label: "跟进内容", key: "searchKey" } },
  { prop: "typeId", label: "跟进方式" },
  { prop: "visitTime", label: "拜访时间" },
  { prop: "nextVisitTime", label: "下次拜访时间" },
  { prop: "remark", label: "备注" },
  { prop: "operation", label: "操作", fixed: "right", width: 180 }
];

// 删除用户信息
const deleteAccount = async (params: User.ResUserList) => {
  await useHandleData(delFollow, { id: params.id }, `删除`);
  proTable.value?.getTableList();
};

// 批量删除用户信息
// const batchDelete = async (id: string[]) => {
//   await useHandleData(deleteUser, { id }, "删除所选用户信息");
//   proTable.value?.clearSelection();
//   proTable.value?.getTableList();
// };

// 导出用户列表
// const downloadFile = async () => {
//   ElMessageBox.confirm("确认导出用户数据?", "温馨提示", { type: "warning" }).then(() =>
//     useDownload(exportUserInfo, "用户列表", proTable.value?.searchParam)
//   );
// };

// 批量添加用户
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);
// const batchAdd = () => {
//   const params = {
//     title: "用户",
//     tempApi: exportUserInfo,
//     importApi: BatchAddUser,
//     getTableList: proTable.value?.getTableList
//   };
//   dialogRef.value?.acceptParams(params);
// };
// 获取所有车型

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof CustomerDrawer> | null>(null);
const openDrawer = async (title: string, row: Partial<User.ResUserList> = {}) => {
  // drawerVisible.value = true;
  try {
    let companyProductsed = [];
    let importanceId = 3;
    let stageId = "";
    if (row.id) {
      const { data } = await getFollowDetail({ id: row.id });
      companyProductsed = (data.companyProducts && data.companyProducts.map(itm => itm.productModelId)) || [];
      importanceId = data.importanceId;
      stageId = data.stageId;
    }

    const params = {
      title,
      isView: title === "查看",
      row: { ...row, companyProductsed, importanceId, stageId },
      api: title === "新增" ? addFollow : title === "编辑" ? updateFollow : undefined,
      getTableList: proTable.value?.getTableList,
      dictList
    };
    drawerRef.value?.acceptParams(params);
  } catch (e) {
    console.log(e);
  }
};
</script>
